package xin.fsqr520.project;

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class HttpLoginClient {
    public static void main(String[] args) {
        // 1. 创建 HttpClient 实例（设置超时时间）
        HttpClient client = HttpClient.newBuilder()
                .connectTimeout(Duration.ofSeconds(10)) // 连接超时
                .build();

        // 2. 构建请求参数（JSON格式）
        Map<String, String> params = new HashMap<>();
        params.put("phoneNumber", "13034468728");
        params.put("password", "123456");

        // 3. 将参数转换为 JSON 字符串（使用 Jackson 库，需添加依赖）
        ObjectMapper objectMapper = new ObjectMapper();
        String jsonBody;
        try {
            jsonBody = objectMapper.writeValueAsString(params);
        } catch (JsonProcessingException e) {
            System.err.println("JSON 转换失败：" + e.getMessage());
            return;
        }

        // 4. 构建 POST 请求
        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create("https://fsqr520.xin/user/login")) // 目标接口地址
                .header("Content-Type", "application/json") // 指定 JSON 格式
                .timeout(Duration.ofSeconds(10)) // 响应超时
                .POST(HttpRequest.BodyPublishers.ofString(jsonBody, StandardCharsets.UTF_8)) // 发送 JSON 体
                .build();

        // 5. 发送请求并处理响应
        try {
            HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
            
            // 打印响应结果
            System.out.println("响应状态码：" + response.statusCode());
            System.out.println("响应体：" + response.body());
        } catch (Exception e) {
            System.err.println("请求失败：" + e.getMessage());
        }
    }
}